<?php
namespace app\agentapi\controller;
use app\agentapi\model\User as AgentUser;
use think\Cache;
use think\Db;
use app\common\library\WsgtLog;
/**
 * 登录控制器
 */
class Passport extends Controller{
    /**
     * 账号密码登录
     */
    public function login(){
        //提交登录信息
        $model = new AgentUser;
        $phone=input('post.phone');
        $password=input('post.password');
        if(empty($phone)){
            return json(['msg'=>'手机号不能为空','code'=>'error','data'=>[]]);
        }
        if(empty($password)){
            return json(['msg'=>'用户密码不能为空','code'=>'error','data'=>[]]);
        }
        $log = WsgtLog::instance();
        $log->setFilename('login/info');
        $log->info($phone, '登录电话');
        $log->info($password, '登录密码');
        $return=$model->agentLogin($phone,$password);
        $log->info($return, '登录状态');
        if($return['code']==1){
			return json(['msg'=>'登陆成功','code'=>'success','data'=>['token'=>Cache::get($return['data']),'userInfo'=>Cache::get($phone)]]);
		}else{
			if($return['code']==-2){
				return json(['msg'=>'该账号已被禁用','code'=>'error','data'=>[]]);
			}
            if($return['code']==-3){
                return json(['msg'=>'该账号所属公司已被禁用','code'=>'error','data'=>[]]);
            }
			return json(['msg'=>'用户名或密码不正确','code'=>'error','data'=>[]]);
		}
    }
    /**
     * 登陆成功获取授权信息
     */
        public function sendCode(){
        //根据code 获取openid和session_key
        //获取微信小程序 appid  和 secret
        $rawData=input('post.rawData');
        $encryptedData=input('post.encryptedData');
        $iv=input('post.iv');
        $signature=input('post.signature');
        $code=input('post.code');
        $agent_wxapp_id=input('post.agent_wxapp_id');
        $agent_user_id=input('post.agent_user_id');
        $rawDataInfo=htmlspecialchars_decode($rawData);
        $rawDataInfo=json_decode($rawDataInfo,'true');
        if(empty($rawData)){
            return json(['msg'=>'rawData参数不能为空','code'=>'error','data'=>[]]);
        }
        if(empty($encryptedData)){
            return json(['msg'=>'encryptedData参数不能为空','code'=>'error','data'=>[]]);
        }
        if(empty($iv)){
            return json(['msg'=>'iv参数不能为空','code'=>'error','data'=>[]]);
        }
        if(empty($signature)){
            return json(['msg'=>'signature参数不能为空','code'=>'error','data'=>[]]);
        }
        if(empty($code)){
            return json(['msg'=>'code参数不能为空','code'=>'error','data'=>[]]);
        }
        if(empty($agent_wxapp_id)){
            return json(['msg'=>'小程序id为空','code'=>'error','data'=>[]]);
        }
        if(empty($agent_user_id)){
            return json(['msg'=>'当前登录代理id不能为空','code'=>'error','data'=>[]]);
        }
        $userInfo=Db::name('agent')->where(['agent_id'=>$agent_user_id])->find();
        $weixinInfo=Db::name('agent_wxapp')->where(['agent_wxapp_id'=>$agent_wxapp_id])->find();
        $appid  = $weixinInfo['app_id'];
        $secret = $weixinInfo['app_secret'];
        //curl请求获得openid,session_key
        $curl="https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$secret}&js_code={$code}&grant_type=authorization_code";
        $res=$this->get_request($curl);
        //\think\Log::info('授权出参：'.$res);
        $res=json_decode($res,true);
        //修改agent_user信息
        /*$data=json_decode($data,true);*/
        Db::name('agent_user')->where(['agent_user_id'=>$agent_user_id])->update([
            'openid'      => $res['openid'],
            'weixinname'    => $rawDataInfo['nickName'],
            'avatar_url'  => $rawDataInfo['avatarUrl']
        ]);
        //修改agent信息
        Db::name('agent')->where(['agent_id'=>$agent_user_id])->update([
            'openid'      => $res['openid'],
            'weixinname'    => $rawDataInfo['nickName'],
            'avatar_url'  => $rawDataInfo['avatarUrl']
        ]);
        //保持代理登录状态
        Cache::set($agent_wxapp_id.'token',$signature,86400*7);
        $loginInfo=Cache::get($agent_wxapp_id.$agent_user_id);
        if($loginInfo['loginUser']['type']==0){
            $loginInfo['loginUser']['type_name']='品牌商';
        }elseif ($loginInfo['loginUser']['type']==1){
            $loginInfo['loginUser']['type_name']='城市运营商';
        }elseif ($loginInfo['loginUser']['type']==2){
            $loginInfo['loginUser']['type_name']='城市合伙人';
        }else{
            $loginInfo['loginUser']['type_name']='代言人';
        }
        $loginInfo['loginUser']['avatar_url']=$rawDataInfo['avatarUrl'];
        $loginInfo['token']=Cache::get($userInfo['user_name'].'token');
        return json(['msg'=>'授权成功','data'=>$loginInfo,'code'=>'success']);
    }
    /*
     * 退出登录
     */
    public function loginOut(){
        $agent_wxapp_id=input('post.agent_wxapp_id');
        $agent_user_id=input('post.agent_user_id');
        $loginInfo=Cache::get($agent_wxapp_id.$agent_user_id);
        if(empty($loginInfo)){
            return json(['msg'=>'登录信息不存在,操作失败','data'=>[],'code'=>'error']);
        }
        //清除登录状态
        if(Cache::rm($agent_wxapp_id.$agent_user_id)){
            return json(['msg'=>'退出成功','data'=>[],'code'=>'success']);
        }
    }
    /*
     * 代理小程序端修改密码
     */
    public function updatePassword(){
        $userName=input('post.user_name');
        $password=input('post.password');
        $weixinId=input('post.weixinId');
        $newPassword=input('post.newPassword');
        if(empty($weixinId)){
            return json(['msg'=>'小程序标识id不能为空','code'=>'error','data'=>[]]);
        }
        if(empty($userName)){
            return json(['msg'=>'登录名称不能为空','code'=>'error','data'=>[]]);
        }
        if(empty($password)){
            return json(['msg'=>'用户密码不能为空','code'=>'error','data'=>[]]);
        }
        if(empty($newPassword)){
            return json(['msg'=>'新密码不能为空','code'=>'error','data'=>[]]);
        }
        $where['user_name']=$userName;
        $agentUserInfos=Db::name('agent_user')->where($where)->find();
        if(empty($agentUserInfos)){
            return json(['msg'=>'该用户名称不存在','data'=>[],'code'=>'error']);
        }
        $salt=$agentUserInfos['salt'];
        $where['password']=md5(md5($password.$salt.config('salt')));
        $agentUserInfo=Db::name('agent_user')->field('password',true)->where($where)->find();
        // var_dump($agentUserInfo);die;
        if($agentUserInfo){
            //判断当前登录代理是否属于所选小程序
            $topAgentIds=Db::name('agent_user')->field('password',true)->where(['pinpai_id'=>$agentUserInfo['pinpai_id'],'type'=>0])->find();
            $topAgentId=$topAgentIds['agent_user_id'];
            //return $topAgentId;
            $wxappInfo=Db::name('agent_wxapp')->where(['agent_id'=>$topAgentId])->field('app_id,app_secret,mchid,apikey,cert_pem,key_pem',true)->find();
            //return $wxappInfo;
            if($wxappInfo){
                if($wxappInfo['agent_wxapp_id']!=$weixinId){
                    return json(['msg'=>'输入账号与所选小程序不匹配','data'=>[],'code'=>'error']);//输入账号与所选小程序不匹配
                }
                //修改密码
                Db::name('agent')->where(['user_name'=>$userName,'password'=>$where['password']])->update(['password'=>md5(md5($newPassword.$agentUserInfo['salt'].config('salt')))]);
                Db::name('agent_user')->where(['user_name'=>$userName,'password'=>$where['password']])->update(['password'=>md5(md5($newPassword.$agentUserInfo['salt'].config('salt')))]);
                return json(['msg'=>'修改成功','data'=>[],'code'=>'success']);
            }else{
                return json(['msg'=>'小程序信息不存在','data'=>[],'code'=>'error']);//小程序信息不存在，
            }
        }else{
            return json(['msg'=>'初始密码不正确','data'=>[],'code'=>'error']);//该用户不存在
        }
    }
    /*
     * curl请求
     */
    private function get_request($url){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $data = curl_exec($curl);
        curl_close($curl);
        return $data;
    }
}
